<template>
  <div class="category-nav">
    <!-- 搜索栏 -->
    <el-row :gutter="15" align="middle" class="search-bar" justify="center">
      <el-col :xs="24" :sm="18" :md="16" :lg="14" :xl="12">
        <el-input
            v-model="searchQuery"
            placeholder="请输入植物名或拉丁文名"
            clearable
            @input="handleSearchInput"
            @keyup.enter.native="performSearch"
            class="search-input"
        >
          <template #prefix>
            <el-icon class="el-input__icon"><search /></el-icon>
          </template>
        </el-input>
      </el-col>

      <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="button-group">
        <el-button
            type="primary"
            @click="performSearch"
            class="search-btn"
            :icon="Search"
            round
        >
          搜索
        </el-button>
        <el-button
            type="warning"
            @click="resetSearch"
            class="reset-btn"
            :icon="Refresh"
            round
        >
          重置
        </el-button>
      </el-col>
    </el-row>

    <!-- 第一行：展示所有大类 -->
    <el-row :gutter="10" style="margin-bottom: 10px;" v-if="!isSearching">
      <el-col :span="2">
        <strong>一级分类：</strong>
      </el-col>
      <el-col :span="22">
        <el-row :gutter="10">
          <el-col :span="4" v-for="category in categories" :key="category.id">
            <el-button
                type="success"
                :class="{ 'active-category': activeCategoryId === category.id.toString() }"
                @click="selectCategory(category)"
                plain
            >
              {{ category.categoryName }}
            </el-button>
          </el-col>
        </el-row>
      </el-col>
    </el-row>

    <!-- 第二行：展示选择大类的子类 -->
    <el-row :gutter="10" v-if="!isSearching">
      <el-col :span="2">
        <strong>二级分类：</strong>
      </el-col>
      <el-col :span="22">
        <el-row :gutter="10">
          <el-col :span="4" v-for="child in currentChildren" :key="child.id">
            <el-button
                type="success"
                :class="{ 'active-subcategory': selectedSubCategoryId === child.id.toString() }"
                @click="selectSubCategory(child)"
                plain
            >
              {{ child.categoryName }}
            </el-button>
          </el-col>
        </el-row>
      </el-col>
    </el-row>

    <!-- 展示选中的子类详情 或者 搜索结果 -->
    <div v-if="selectedSubCategory || isSearching" class="plant-card-content" style="left: 10px;">
      <div v-if="plants.data.list.length > 0">
        <el-row :gutter="20">
          <el-col :span="6" v-for="plant in plants.data.list" :key="plant.id">
            <el-card shadow="hover" @click="navTo('/front/plantDetail?id=' + plant.plantInfoId)" class="uniform-card">
              <img :src="plant.plantImg" alt="" class="plant-image" @error="handleImageError($event)">
              <div class="card-content">
                <h4 class="ellipsis" :title="plant.chineseName">{{ plant.chineseName }}</h4>
                <p class="ellipsis" :title="'别名：' + plant.aliases"><strong>别名：</strong> {{ plant.aliases }}</p>
                <p class="ellipsis" :title="'形态：' + plant.morphology"><strong>形态：</strong> {{ plant.morphology }}</p>
                <p class="ellipsis" :title="'分布：' + plant.distribution"><strong>分布：</strong> {{ plant.distribution }}</p>
                <p class="ellipsis" :title="'应用：' + (plant.application || '无')"><strong>应用：</strong> {{ plant.application || '无' }}</p>
                <p class="ellipsis" :title="'拉丁名：' + (plant.latinName || '无')"><strong>拉丁名：</strong> {{ plant.latinName || '无' }}</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <!-- 分页组件 -->
        <el-pagination
            background
            layout="prev, pager, next"
            :total="plants.data.total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
            style="margin-top: 20px; text-align: center;"
        />
      </div>
      <el-empty v-else description="暂无数据" />
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, computed } from 'vue';
import request from "@/utils/request.js";
import { ElMessage } from "element-plus";
import {Refresh, Search} from "@element-plus/icons-vue";

const categories = ref([]);
const activeCategoryId = ref(null); // 当前激活的父分类ID
const selectedSubCategoryId = ref(null); // 当前激活的子分类ID
const selectedSubCategory = ref(null);
const plants = ref({ data: { list: [], total: 0 } }); // 存储植物数据
const currentPage = ref(1); // 当前页码
const pageSize = 10; // 每页显示的数量
const searchQuery = ref(''); // 搜索查询字符串
const isSearching = ref(false); // 是否正在进行搜索

// 加载植物分类
const loadPlantClass = () => {
  request.get('/plantClass/selectAll').then(res => {
    if (res.code === '200') {
      categories.value = res.data.map(category => ({
        id: category.id,
        categoryName: category.categoryName,
        children: category.children ? category.children.map(child => ({
          id: child.id,
          categoryName: child.categoryName
        })) : []
      }));
      // 默认选择第一个分类及其子分类（如果有）
      if (categories.value.length > 0) {
        activeCategoryId.value = categories.value[0].id.toString();
        const firstCategory = categories.value[0];
        if (firstCategory.children && firstCategory.children.length > 0) {
          selectSubCategory(firstCategory.children[0]);
        } else {
          selectedSubCategory.value = firstCategory;
          loadPlants(firstCategory.id);
        }
      }
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    console.error("加载分类失败：", err);
    ElMessage.error("加载分类失败，请检查接口或网络连接");
  });
};

// 处理大类选择
const selectCategory = (category) => {
  activeCategoryId.value = category.id.toString();
  if (category.children && category.children.length > 0) {
    selectSubCategory(category.children[0]);
  } else {
    selectedSubCategory.value = category;
    selectedSubCategoryId.value = null;
    loadPlants(category.id);
  }
};

// 处理子类选择
const selectSubCategory = (subCategory) => {
  selectedSubCategory.value = subCategory;
  selectedSubCategoryId.value = subCategory.id.toString();
  loadPlants(subCategory.id);
};

// 计算当前选择的大类的子类
const currentChildren = computed(() => {
  const activeCategory = categories.value.find(cat => cat.id.toString() === activeCategoryId.value);
  return activeCategory ? activeCategory.children : [];
});

// 加载植物数据
const loadPlants = (categoryId) => {
  request.get(`/plant/selectById/${categoryId}`, {
    params: {
      pageNum: currentPage.value,
      pageSize: pageSize
    }
  }).then(res => {
    if (res.code === '200') {
      console.log('Loaded plants:', res.data.list); // 添加调试信息
      plants.value = res;
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    console.error("加载植物数据失败：", err);
    ElMessage.error("加载植物数据失败，请检查接口或网络连接");
  });
};

// 图片加载错误处理
const handleImageError = (event) => {
  event.target.onerror = null; // 避免无限循环
  event.target.src = 'https://via.placeholder.com/150'; // 替换为占位图
};

// 处理分页变化
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  if (isSearching.value) {
    performSearch();
  } else {
    loadPlants(selectedSubCategoryId.value || activeCategoryId.value);
  }
};

const navTo = (url) => {
  location.href = url;
};

// 初始化加载
loadPlantClass();

// 搜索相关方法
const handleSearchInput = () => {
  // 清除之前的选择
  activeCategoryId.value = null;
  selectedSubCategoryId.value = null;
  selectedSubCategory.value = null;

  // 如果搜索框为空，则重置视图
  if (!searchQuery.value.trim()) {
    resetSearch();
  }
};

const performSearch = () => {
  if (!searchQuery.value.trim()) {
    ElMessage.warning("请输入搜索关键词");
    return;
  }

  isSearching.value = true;

  request.get('/plant/selectByPlantName', {
    params: {
      pageNum: currentPage.value,
      pageSize: pageSize,
      plantName: searchQuery.value
    }
  }).then(res => {
    if (res.code === '200') {
      console.log('Search results:', res.data.list); // 添加调试信息
      plants.value = res;
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    console.error("搜索失败：", err);
    ElMessage.error("搜索失败，请检查接口或网络连接");
  });
};

const resetSearch = () => {
  searchQuery.value = '';
  isSearching.value = false;
  activeCategoryId.value = null;
  selectedSubCategoryId.value = null;
  selectedSubCategory.value = null;
  currentPage.value = 1;
  loadPlantClass(); // 重新加载分类并选择默认项
};
</script>

<style scoped>
/* 原始导航按钮样式保留（添加作用域隔离） */
.category-nav :deep(.el-button) {
  width: 100%;
  margin-bottom: 5px;
  transition: background-color 0.3s ease, border-color 0.3s ease;
}

.category-nav :deep(.el-button:hover) {
  background-color: #e6f7ff;
  border-color: #bae7ff;
}

.category-nav :deep(.el-button.active-category) {
  background-color: #ecf5ff;
  border-color: #d9ecff;
  color: #409eff;
}

.category-nav :deep(.el-button.active-subcategory) {
  background-color: #e6f7ff;
  border-color: #bae7ff;
  color: #1890ff;
}

/* 卡片样式（加强作用域限制） */
.plant-card-content :deep(.uniform-card) {
  height: 350px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.plant-card-content :deep(.el-card__body) {
  display: flex !important;
  flex-direction: column;
  height: 100%;
  padding: 0;
}

.plant-card-content :deep(.plant-image) {
  width: 100%;
  height: 150px;
  min-height: 150px;
  object-fit: cover;
  flex-shrink: 0;
}

.plant-card-content :deep(.card-content) {
  flex: 1;
  padding: 10px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.plant-card-content :deep(.card-content > *) {
  flex-shrink: 0;
  margin: 0;
  line-height: 1.4;
  min-height: 1.4em;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.plant-card-content :deep(.card-content h4) {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

/* 第一个卡片特殊处理 */
.plant-card-content :deep(.el-col:first-child .el-card) {
  line-height: initial;
}

/* 搜索栏容器 */
.search-bar {
  margin-bottom: 20px;
  padding: 12px 20px;
  background: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 输入框样式 */
.search-input :deep(.el-input__wrapper) {
  border-radius: 20px;
  padding: 0 20px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.search-input :deep(.el-input__prefix) {
  left: 12px;
  display: flex;
  align-items: center;
}

/* 按钮组样式 */
.button-group {
  display: flex;
  gap: 12px;
  padding-left: 15px;
}

.search-btn,
.reset-btn {
  padding: 10px 25px;
  font-weight: 500;
  letter-spacing: 0.5px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.search-btn {
  background: linear-gradient(135deg, #409eff, #3375ff);
  border: none;
}

.reset-btn {
  background: linear-gradient(135deg, #e6a23c, #d9822b);
  border: none;
}

/* 响应式处理 */
@media (max-width: 768px) {
  .button-group {
    padding-left: 0;
    margin-top: 15px;
    justify-content: flex-end;
  }

  .search-input :deep(.el-input) {
    width: 100%;
  }
}
</style>
